## Compartimentalizacao - BPSR


library(readr)
library(factoextra)
library(foreign)
library(ggplot2)
library(reshape2)
library(dplyr)
library(jtools)
library(fpc)
library(cowplot)
library(ggpubr)
library(stargazer)
library(interactions)


load("Compartimentalizacao.Rda")




## Graficos Ministerios

attach(min2)

# Figura 2

mean.policy <- aggregate(TotalIniciativas~Ministry, min2, mean)
mean.policy <- mean.policy[-c(10), ]
sd.policy <- aggregate(TotalIniciativas~Ministry, min2, sd)
sd.policy <- sd.policy[-c(10), ]


mean.sd.policy <- cbind(mean.policy, sd.policy$TotalIniciativas)

names(mean.sd.policy)[names(mean.sd.policy) == 'sd.policy$TotalIniciativas'] <- 'sd'

limits2 <- aes(ymax = TotalIniciativas + sd, ymin=TotalIniciativas - sd)

policy<-ggplot(mean.sd.policy, aes(x = reorder(Ministry, -TotalIniciativas), y = TotalIniciativas)) +
  geom_point() + geom_pointrange(limits2) + labs(x="",y="Policies") + 
  theme_bw() + theme(text=element_text(family="Arial Black", size=14)) +
  theme(axis.text.x=element_text(angle=90))



mean.office <- aggregate(DepNDAS5e6~Ministry, min2, mean)
mean.office <- mean.office[-c(10), ]
sd.office <- aggregate(DepNDAS5e6~Ministry, min2, sd)
sd.office <- sd.office[-c(10), ]

mean.sd.office <- cbind(mean.office, sd.office$DepNDAS5e6)


names(mean.sd.office)[names(mean.sd.office) == 'sd.office$DepNDAS5e6'] <- 'sd'

limits3 <- aes(ymax = DepNDAS5e6 + sd, ymin=DepNDAS5e6 - sd)

estrutu<-ggplot(mean.sd.office, aes(x = reorder(Ministry, -DepNDAS5e6), y = DepNDAS5e6)) +
  geom_point() + geom_pointrange(limits3) + labs(x="",y="Structures") + 
  theme_bw() + theme(text=element_text(family="Arial Black", size=14)) +
  theme(axis.text.x=element_text(angle=90))

plot_grid(estrutu, policy)


#Figura 3

mean.budget <- aggregate(LogTotal~Ministry, min2, mean)
mean.budget <- mean.budget[-c(10), ]
sd.budget <- aggregate(LogTotal~Ministry, min2, sd)
sd.budget <- sd.budget[-c(10), ]
mean.sd.budget <- cbind(mean.budget, sd.budget$LogTotal)

names(mean.sd.budget)[names(mean.sd.budget) == 'sd.budget$LogTotal'] <- 'sd'

limits <- aes(ymax = LogTotal + sd, ymin=LogTotal - sd)

budgtot<-ggplot(mean.sd.budget, aes(x = reorder(Ministry, -LogTotal), y = LogTotal)) +
  geom_point() + geom_pointrange(limits) + labs(x="",y="Total Budget") + theme_bw() +
  theme(text=element_text(family="Arial Black", size=14)) +
  theme(axis.text.x=element_text(angle=90))


mean.budget <- aggregate(LogInvest~Ministry, min2, mean)
mean.budget <- mean.budget[-c(10), ]
sd.budget <- aggregate(LogInvest~Ministry, min2, sd)
sd.budget <- sd.budget[-c(10), ]
mean.sd.budget <- cbind(mean.budget, sd.budget$LogInvest)

names(mean.sd.budget)[names(mean.sd.budget) == 'sd.budget$LogInvest'] <- 'sd'

limits <- aes(ymax = LogInvest + sd, ymin=LogInvest - sd)

budginv<-ggplot(mean.sd.budget, aes(x = reorder(Ministry, -LogInvest), y = LogInvest)) +
  geom_point() + geom_pointrange(limits) + labs(x="",y="Invest. Budget") + theme_bw() +
  theme(text=element_text(family="Arial Black", size=14)) +
  theme(axis.text.x=element_text(angle=90))

plot_grid(budgtot, budginv)


## Cluster

minr <- subset(min2, select = c(Ministry,TotalIniciativas,LogTotal, LogInvest, DepNDAS5e6))

attach(minr)
mina<-aggregate(minr, by=list(Ministry),FUN=mean, na.rm=TRUE)

mina <- mina[-c(10), ]


minac <- subset(mina, select = -c(Ministry))

minac <- na.omit(minac)

rownames(minac) <- minac[,1]
minac <- subset(minac, select = -c(Group.1))

minc <- scale(minac)
head(minc,n=5)

fviz_nbclust(minc, kmeans, method = "wss") +
  geom_vline(xintercept = 6, linetype = 2)

set.seed(123)
km.res <- kmeans(minc, 5, nstart = 50)
print(km.res)

km.res$size

#Figure 4

fviz_cluster(km.res, data = minc,
             palette = c("black", "darkgreen", "brown4", "red2","navyblue","darkgrey"),             star.plot = TRUE, # Add segments from centroids to items
             repel = TRUE, # Avoid label overplotting (slow)
             main = "",
             ggtheme = theme_minimal()
)

km_stats <- cluster.stats(dist(minac),  km.res$cluster)
km_stats



minclus <- cbind(minac, cluster = km.res$cluster)
head(minclus)


minclus <- add_rownames(minclus, "Ministry")

minf <- merge(min2, minclus, by = c("Ministry"), all.x=T)


###


minf$Cluster <- as.factor(minf$cluster)

levels(minf$Cluster)[levels(minf$Cluster)==1] <- "Regulation"
levels(minf$Cluster)[levels(minf$Cluster)==4] <- "Coordination"
levels(minf$Cluster)[levels(minf$Cluster)==3] <- "Redistribution-Social"
levels(minf$Cluster)[levels(minf$Cluster)==5] <- "Distribution"
levels(minf$Cluster)[levels(minf$Cluster)==2] <- "Redistribution-Labor"


## Regressao


minf2 <- minf[-c(18,49,148,151), ] #remove observaçoes sem ministro 


minf2$Cluster3 <- minf2$Cluster
minf2$Cluster3 <- relevel(minf2$Cluster3, ref="Coordination")


minf2$Minister <-as.factor(minf2$TipoMinistro)
levels(minf2$Minister)[levels(minf2$Minister)=="Nao-Partidario"] <- "Non-Partisan"
levels(minf2$Minister)[levels(minf2$Minister)=="Parceiro da Coalizao"] <- "Coalition Partner"
levels(minf2$Minister)[levels(minf2$Minister)=="Partido do Presidente"] <- "President's Party"

levels(minf2$Cluster3)


# Tabela 2

m1 <- lm(Prop_DAS56_setorpublico~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)
m2 <- lm(Prop_DAS14_setorpublico~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)

m3 <- lm(prop_DAS56_affiliation_total~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)
m4 <- lm(prop_DAS14_affiliation_total~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)

summary(m1)
stargazer(m1, m2, m3, m4, title="Public Sector - Affiliated", type="html",out="PublicSectorAffiliated.doc")


# Tabela 3

m1 <- lm(prop_DAS5.6_president_tot~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)
m2 <- lm(prop_DAS1.4_president_tot~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)

m3 <- lm(prop_DAS56_affiliation_coalition_tot~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)
m4 <- lm(prop_DAS14_affiliation_coalition_tot~Cluster3+Minister+Popularity+TimeElection+Governo, data = minf2)


stargazer(m1, m2, m3, m4, title="Affiliated", type="html",out="Affiliated.doc")


# Figura 5

cat1<-cat_plot(m1, pred = Cluster3, modx = Minister)
cat1<-cat1 + labs(x="",y="President's Party") +
  theme(text=element_text(family="Arial", size=14)) +
  theme(axis.text.x=element_text(angle=90))+
  ggtitle("DAS 5-6") + scale_colour_manual(values=c("black","darkgrey","navyblue","darkred"))



cat2<-cat_plot(m2, pred = Cluster3, modx = Minister)
cat2<-cat2 + labs(x="",y="President's Party") +
  theme(text=element_text(family="Arial", size=14)) +
  theme(axis.text.x=element_text(angle=90))+
  ggtitle("DAS 1-4") + scale_colour_manual(values=c("black","darkgrey","navyblue"))

ggarrange(cat1,cat2, ncol=2, nrow=1, common.legend = TRUE, legend="bottom")


# Figura 6

cat3<-cat_plot(m3, pred = Cluster3, modx = Minister)
cat3<-cat3 + labs(x="",y="Coalition Partner") +
  theme(text=element_text(family="Arial", size=14)) +
  theme(axis.text.x=element_text(angle=90))+
  ggtitle("DAS 5-6") + scale_colour_manual(values=c("black","darkgrey","navyblue","darkred"))



cat4<-cat_plot(m4, pred = Cluster3, modx = Minister)
cat4<-cat4 + labs(x="",y="Coalition Partner") +
  theme(text=element_text(family="Arial", size=14)) +
  theme(axis.text.x=element_text(angle=90))+
  ggtitle("DAS 1-4") + scale_colour_manual(values=c("black","darkgrey","navyblue"))



ggarrange(cat3,cat4, ncol=2, nrow=1, common.legend = TRUE, legend="bottom")


#Tabela 1

stargazer(minf2, type="html",out="DescritivasBPSR.doc")


